//设备uniqure_code   站点MONITOROWNNETID
var MONITOROWNNETID=GetQueryString("MONITOROWNNETID");
var uniqure_code=GetQueryString("uniqure_code");
var urlStartTime = GetQueryString("startTime");
var urlEndTime =  GetQueryString("endTime");
var initialization =true;

var hightChartData=[];
(function () {
    GetAnalysisWindowFiterTimes('speedratechart_time', 'd', false); 
    //时间组件绑定值
    GetAnalysisWindowFiterTimes('table_time', 'd', false);
    //单选绑定事件
    $("#TimeSelectionBox input[type='radio']").click(function () {
        showTimeBox()
        LoadSpeedRateChartData();
    });

        //天周月切换绑定事件
    $("#speedratewindow").on('click', ".timefiltercontent a", function () {
        var type = $(this).data("type");
        $(this).addClass('active').siblings().removeClass('active');
        GetAnalysisWindowFiterTimes('speedratechart_time', type, false);
        LoadSpeedRateChartData();
    });
    $('#speedratewindow #speedratechart_time').daterangepicker(null, function (start, end, label) {
        times = $("#speedratewindow #speedratechart_time").val();
        LoadSpeedRateChartData();
    });

    //选择日期触发事件
    $('#speedratewindow2 #table_time').daterangepicker(null, function (start, end, label) {
        times = $("#speedratewindow2 #table_time").val();
        getTableData(times);
    });
    //天周月切换绑定事件
    $("#speedratewindow2").on('click', ".timefiltercontent a", function () {
        var type = $(this).data("type");
        $(this).addClass('active').siblings().removeClass('active');
        GetAnalysisWindowFiterTimes('table_time', type, false);
        getTableData();
    });
    if(MONITOROWNNETID !=null ){
        let url = "http://119.97.193.69:97/Jcwlw/Other/getDeviceListByNetId?MONITOROWNNETID="+MONITOROWNNETID;
        $.get(url, function (res) {
            let resData = JSON.parse(res);
            if(resData.data.length>0){
                resData.data.forEach((li)=>{
                    if(li.TYPE == 212){
                        li.list.forEach((item)=>{
                            //JCAA03A010   JCAA03A018中文
                           // $("#ChartTableSelect").append("<option value='"+item.JCAA03A010+"'>"+item.JCAA03A010+"</option>");
                           $("#ChartSelect").append("<option value='"+item.JCAA03A010+"'>"+item.JCAA03A010+"</option>");
                           $("#TableSelect").append("<option value='"+item.JCAA03A010+"'>"+item.JCAA03A010+"</option>");
                        })
                    }
                })
            }
            getAllData();
        })
    }else if(uniqure_code !=null){
        // $("#ChartTableSelect").append("<option value='"+uniqure_code+"'>"+uniqure_code+"</option>");
        $("#ChartSelect").append("<option value='"+uniqure_code+"'>"+uniqure_code+"</option>");
        $("#TableSelect").append("<option value='"+uniqure_code+"'>"+uniqure_code+"</option>");
        getAllData();
    }
})();
//获取浏览器的参数
function GetQueryString(name){
    var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if(r!=null)return  unescape(r[2]); return null;
}
//日期选择函数
function GetAnalysisWindowFiterTimes(valuetoid, type, event) {
    var ntime = new Date();
    if (type == 'd') {
        var dstart = ntime.format("MM/dd/yyyy");
        var dend = ntime.format("MM/dd/yyyy");
        $(".timeControl #" + valuetoid).val(dstart + " - " + dend);
    } else if (type == 'w') {
        var wstart = new Date(ntime.getTime() + (24 * 60 * 60 * -6 * 1000)).format("MM/dd/yyyy");
        var wend = ntime.format("MM/dd/yyyy");
        $(".timeControl #" + valuetoid).val(wstart + ' - ' + wend);
    } else if (type == 'm') {
        var mstart = new Date(ntime.getTime() + (24 * 60 * 60 * -30 * 1000)).format("MM/dd/yyyy");
        var mend = ntime.format("MM/dd/yyyy");
        $(".timeControl #" + valuetoid).val(mstart + ' - ' + mend);
    }
    eval(event);
}
//获取chart的数据和table的数据
function getAllData(){
    LoadSpeedRateChartData();
    getTableData();
    initialization=false;
}
//判断是日还是天
function showTimeBox(){
    let initializationType = $("#TimeSelectionBox input[type='radio']:checked").val();
    let TimeArr=[];
    if(initializationType =='hour' ){
        hightChartData.forEach((li)=>{
            if(TimeArr.indexOf(li.time) == -1){
                TimeArr.push(li.time)
            }
        })
        let html="";
        TimeArr.forEach((item)=>{
            html+="<p>"+ item +"</p>";
        })
        $(".speedratechartRight").html(html);
    }else{
        let times = $("#speedratechart_time").val();
        var startTimeSplit = times.split('-')[0].replace(" ", "").split('/'),
        endTimeSplit = times.split('-')[1].replace(" ", "").split('/');
        var first = startTimeSplit[2] + "-" + startTimeSplit[0] + "-" + startTimeSplit[1];
        var last = endTimeSplit[2] + "-" + endTimeSplit[0] + "-" + endTimeSplit[1];
        let dayNum = datedifference(first,last);
        let dayTime = [];
        for(let a=0;a<=dayNum;a++){
            let day=new Date(last)
            day.setDate(day.getDate() - a)
            dayTime.unshift(new Date(day).format("yyyy-MM-dd"))
        }
        let html="";
        dayTime.forEach((limi)=>{
            html += "<p>"+ limi +"</p>";
        })
        $(".speedratechartRight").html(html); 
    }
    $(".speedratechartRight p:first").addClass('selectBg');
    $(".speedratechartRight").on("click","p",function(){   
        $(this).addClass('selectBg').siblings().removeClass('selectBg');
        InstallationSpeedRateDataAnalysisWindowData();
    });

}
function chartSensorSelectChange(){
    var SelectSensorVal = $('#ChartSelect  option:selected').val();
    getChartData(SelectSensorVal)
}
function datedifference(sDate1, sDate2) {    //sDate1和sDate2是2006-12-18格式 
    var dateSpan,
        tempDate,
        iDays;
        sDate1 = Date.parse(sDate1);
        sDate2 = Date.parse(sDate2);
        dateSpan = sDate2 - sDate1;
        dateSpan = Math.abs(dateSpan);
        iDays = Math.floor(dateSpan / (24 * 3600 * 1000));
        return iDays
};
function LoadSpeedRateChartData(val) {
    let selectVal = $("#ChartSelect option:selected").val();//获取选中项的值
    let timeVal=$("#speedratechart_time").val();
    if(initialization && urlStartTime && urlEndTime){
        var startTime = urlStartTime;
        var endTime = urlEndTime;
    }else if(val){
        var startTime = val+" 00:00:00";
        var endTimeSplit = timeVal.split('-')[1].replace(" ", "").split('/');
        var endTime = endTimeSplit[2] + "-" + endTimeSplit[0] + "-" + endTimeSplit[1]+" 23:59:59";

    }else{
        var startTimeSplit = timeVal.split('-')[0].replace(" ", "").split('/'),
            endTimeSplit = timeVal.split('-')[1].replace(" ", "").split('/');
        var startTime = startTimeSplit[2] + "-" + startTimeSplit[0] + "-" + startTimeSplit[1]+" 00:00:00";
        var endTime = endTimeSplit[2] + "-" + endTimeSplit[0] + "-" + endTimeSplit[1]+" 23:59:59";
    }
     if (selectVal == "") {
        $("#speedratewindow #speedratechart").html("<label>传感器选择不正确，无法加载数据!</label>");
        return;
    }
    var postUrl = "http://192.168.9.59:801/apis/result/query212a?startTime="+ startTime +"&endTime="+ endTime +"&uniqure_code=" + selectVal;
    //请求

    $.get(postUrl, function (result) {
          if (result.msg == "success" && result.data && result.data.length>0) {
            hightChartData=[];
                let data=result.data;
                let column=result.column;
                for(let a=0;a<data.length;a++){
                    let li={}
                    for(let b=0;b<column.length;b++){
                            let key =column[b];
                            li[column[b]]=data[a][b];
                    }
                    hightChartData.push(li)
                }
                showTimeBox(hightChartData);
                InstallationSpeedRateDataAnalysisWindowData(hightChartData);
          } else {

                $("#speedratewindow #speedratechart").html("<label>未能成功加载GNSS数据!</label>");
                $(".speedratechartRight").html("暂无数据");
          }
    });

    
    
}

function InstallationSpeedRateDataAnalysisWindowData() {
    let MarkeTime=$(".selectBg").html();
    let initializationType = $("#TimeSelectionBox input[type='radio']:checked").val();
    var tempData = [];
    //格式化x
    var temp_x = {};
    temp_x.name = "x方向";
    // temp_x.dataType = "0";
    temp_x.data = [];
    //格式化y
    var temp_y = {};
    temp_y.name = "y方向";
    //  temp_y.dataType = "0";
    temp_y.data = [];
    //格式化z
    var temp_z = {};
    temp_z.name = "z方向";
    // temp_z.dataType = "0";
    temp_z.data = [];

    if(initializationType =='hour' ){
        hightChartData.forEach((li)=>{
            // temp_x.data.push([new Date(li.time).getTime(), li.JCSJ212A070]);
            if(li.time == MarkeTime){
                temp_x.data.push({y:li.JCSJ212A070*1,time:li.time});
                temp_y.data.push( {y:li.JCSJ212A070*1,time:li.time});
                temp_z.data.push({y:li.JCSJ212A070*1,time:li.time});
            }
        })
    }else{
        hightChartData.forEach((li)=>{
            // temp_x.data.push([new Date(li.time).getTime(), li.JCSJ212A070]);
            if(li.time.indexOf(MarkeTime)>-1){
                temp_x.data.push({y:li.JCSJ212A070*1,time:li.time});
                temp_y.data.push( {y:li.JCSJ212A070*1,time:li.time});
                temp_z.data.push({y:li.JCSJ212A070*1,time:li.time});
            }
        })
    }

    
    tempData.push(temp_x);
    tempData.push(temp_y);
    tempData.push(temp_z);
    
    var chartData = tempData;

 if (chartData != "") {
    var accumulativeChartType = [0];
    var accumulativeDataUnits = ["深部位移", "mm"];
    var timeFormatUnit = "yyyy-MM-dd hh:mm:ss";
    var showChartDatas = [];
    var nDatas = chartData;
    for (var j = 0; j < chartData.length; j++) {
        nDatas[j].name = nDatas[j].name;
        nDatas[j].type='line';
        showChartDatas.push(nDatas[j]);
    }
        let option={
            chart: {
                    type: 'line',
                    style: {fontFamily: "'Unica One', sans-serif"},
                    plotBorderColor: '#606063',
                    zoomType: 'x',
                    spacingRight: 20,
                    height: 300
            },
            colors: ['#E5561F', '#7FBF7F', '#7F7FFF', '#FF6F10', '#8756D8', '#310F39', '#FF7F7F'],
            title: {text: ''},
            credits: {enabled: false},
            exporting: {enabled: false},
            subtitle: {text: ''},
            tooltip: {
                    formatter: function () {
                       if(initializationType =='hour'){
                        return  "<br>时间:[" + MarkeTime + "]<br>合位移:[" + this.y + "]<br>深度:[" + this.x + "]";
                       }else{
                        return  "<br>时间:[" + this.point.options.time + "]<br>合位移:[" + this.y + "]<br>深度:[" + this.x + "]";
                       }
                        
                    }
            },
            plotOptions: {
                    spline: {
                        lineWidth: 1.5,
                        states: {hover: {lineWidth: 2.5}},
                        marker: {enabled: false}
                    }
            },
            yAxis: [{ // Primary yAxis
                title: {
                    text: '位移（mm）',
                    style: {
                        color: '#89A54E'
                    }
                },
            }],
            xAxis: {
                title: {
                    text: '深度（m）',
                    style: {
                        color: '#89A54E'
                    }
                },
            },
            series: showChartDatas
        }
        $('#speedratewindow #speedratechart').highcharts(option);
    } else {
            $("#speedratewindow #speedratechart").html("<label>未能成功加载GNSS分析数据!</label>");
    }
}
function getTableData(val){
    var selectVal = $("#TableSelect option:selected").val();//获取选中项的值
    var times;
     // var times = $("#speedratewindow2 #table_time").val();
    if(initialization && urlStartTime && urlEndTime){
        var startTime = urlStartTime;
        var endTime = urlEndTime;
    }else if(val){
        times=val;
        var startTimeSplit = times.split('-')[0].replace(" ", "").split('/'),
        endTimeSplit = times.split('-')[1].replace(" ", "").split('/');
        var startTime = startTimeSplit[2] + "-" + startTimeSplit[0] + "-" + startTimeSplit[1]+" 00:00:00";
        var endTime = endTimeSplit[2] + "-" + endTimeSplit[0] + "-" + endTimeSplit[1]+" 23:59:59";
    }else{
        times = $("#speedratewindow2 #table_time").val(); 
        var startTimeSplit = times.split('-')[0].replace(" ", "").split('/'),
        endTimeSplit = times.split('-')[1].replace(" ", "").split('/');
        var startTime = startTimeSplit[2] + "-" + startTimeSplit[0] + "-" + startTimeSplit[1]+" 00:00:00";
        var endTime = endTimeSplit[2] + "-" + endTimeSplit[0] + "-" + endTimeSplit[1]+" 23:59:59";
    }
   
   
   

    var postUrl = "http://192.168.9.59:801/apis/result/query212a/?startTime="+ startTime +"&endTime="+ endTime +"&uniqure_code=" + selectVal;
    //请求
    let tableData=[];
    $.get(postUrl, function (result) {
          if (result.msg == "success" && result.data && result.data.length>0) {
                let data=result.data;let column=result.column;
                for(let a=0;a<data.length;a++){
                      let li={}
                      for(let b=0;b<column.length;b++){
                            let key =column[b];
                            li[column[b]]=data[a][b];
                      }
                      tableData.push(li)
                }
                layui.use(['table','layer','form','laydate'], function(){
                    var table = layui.table;
                    var layer=layui.layer;
                    var form=layui.form;
                    var $=layui.$;
                    var laydate = layui.laydate;
                    //初始赋值
                    table.render({
                            elem: '#idTest'
                            // ,url:'./json/AlarmInformation.json'
                            ,data: tableData
                            ,contentType: "application/x-www-form-urlencoded"
                            ,page: { //支持传入 laypage 组件的所有参数（某些参数除外，如：jump/elem） - 详见文档
                                layout: [ 'prev', 'page', 'next', 'skip','limit', 'count',] //自定义分页布局
                                //,curr: 5 //设定初始在第 5 页
                                ,limit:10 //一页显示多少条
                                ,limits:[5,10,15]//每页条数的选择项
                                ,groups: 2 //只显示 2 个连续页码
                                ,first: "首页" //不显示首页
                                ,last: "尾页" //不显示尾页
                                }
                                ,where:{ispage: true }
                                ,even:true
                                ,page: true  //是否启用分页
                                ,done:function(res, curr, count){}
                            ,cols: [[
                                // ,{field:'JCSJ204A050', title: '设备唯一编码'}
                                ,{field:'time',width:160, title: '时间'}
                                ,{field:'JCSJ212A030',width:80, title: 'X'}//南北方向相对位移值（毫米）
                                ,{field:'JCSJ212A031',width:80, title: 'Y'}//东西方向相对位移值（毫米）
                                ,{field:'JCSJ212A032',width:80, title: 'Z'}//垂直方向相对位移值（毫米）
                                ,{field:'JCSJ212A040', title: '设备入库时间'}
                                ,{field:'JCSJ212A050',width:160, title: '设备唯一编码'}
                                ,{field:'JCSJ212A060',width:160, title: '设备类型编号'}//（如:101）
                                ,{field:'JCSJ212A070', title: '深度'}
              //time 时间
               //JCSJ212A030	NUMBER(20,4)	20	4	Y			X（毫米）
               //JCSJ212A031	NUMBER(20,4)	20	4	Y			Y（毫米）
               //JCSJ212A032	NUMBER(20,4)	20	4	Y			Z（毫米）
               //JCSJ212A040	date	23	0	Y			设备入库时间
               //JCSJ212A050	varchar2(40)	40	0	Y			设备唯一编码
               //JCSJ212A060	varchar2(10)	10	0	Y			设备类型编号（如:101）
               //JCSJ212A070	varchar2(10)	10	0	Y			传感器
                            ]]
                    });
            
                });
          } else {
                $("#tableBox").html("<label>暂无数据!</label>");
          }
    });
}
